#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include "conio.h"

#define MAX_LEN 120		//栈的最大容量
typedef char ElemType;	//数据的类型
ElemType PASSWORD[10]="13579";
typedef struct SqStack
{
	ElemType * data;//data指向一块地址连续的空间，来存储栈的每一个元素
	int top;//栈顶，指定栈顶元素的下标				// top == -1   表示栈中没有元素，空栈
}sq;

//初始化一个栈
sq *InitStack()		
{
	struct SqStack * s = malloc( sizeof(struct SqStack) );
	s->data = malloc(sizeof(ElemType) * MAX_LEN);	
	s->top = -1;					
	return s;
}
//判断是否为空栈
int IsEmpty(struct SqStack * s)
{
	//栈为空：栈不存在 || 栈里面没有元素
	if( s == NULL || s->top == -1 )
	{
		return 1;
	}
	return 0;
}

//判断栈满
int IsFull(sq *s)
{
	return (s->top==MAX_LEN-1);//从
}
//入栈 1成功 0失败
int Push(sq *s,ElemType d)
{
	if(IsFull(s)||s==NULL)
	{
		printf("Push error! \n");
		return 0;	
	}
	else
	{
		s->data[++s->top]=d;
		return 1;
	}
}
//出栈
int Pop(sq *s,ElemType *x)
{
	if(IsEmpty(s)||s==NULL)
	{
		printf("Pop error! \n");
		return 0;
	}
	else
	{
		*x=s->data[s->top--];
		return 1;
	}
}
void CleanStack(sq	*s)
{
	memset(s->data,0,MAX_LEN);
	s->top=-1;
}
void PwdSet(sq *s)
{
	int i=0,j=1,k=0;
	ElemType x,*a;
	ElemType pwd;
	int pwdlen=strlen(PASSWORD);
	//printf("pwdlen:%d",pwdlen);
	while(1)
	{
		if(j>=1&&j<=3)
		{
			//输入密码:
			printf("please input password:\n");
			for(i=0;i<pwdlen;i++)
			{
				pwd=getch();
				printf("*");
				Push(s,pwd);
			}
			a=(ElemType *)malloc(pwdlen*sizeof(ElemType));
			for(i=pwdlen-1;i>=0;i--)
			{
				Pop(s, &x);
				a[i]=x;
				//printf("\n----a[%d]=%c---\n",i,a[i]);
			}
			for(i=0;i<pwdlen;i++)
			{
				//printf("\n----PASSWORD%c---\n",PASSWORD[i]);
				if(PASSWORD[i]==a[i])
				{
					k++;
					//printf("\n----PASSWORD[%d]=%c---\n",i,PASSWORD[i]);
				}
			}
			//printf("\n{k==%d}\n",k);
			if(k!=pwdlen)
			{	
				printf("\npassword wrong!\n");
				if(j!=3)
				printf("You have %d chance\n",3-j);
				j++;
				k=0;
			}
			else
			{
				printf("\npassword right!\n");
				break;
			}
		}
		else
		{
			printf("Have no chance!,It will quit\n");
			break;
		}
	}
	free(a);
}

int main()
{
	sq *s=InitStack();
	
	PwdSet(s);
	return 0;
}

